package com.earogya.logic.pharmacy.request;

import java.util.Calendar;
import java.util.List;
import org.apache.struts.pharmacy.pharmacy.model.PrescriptionDrugs;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.DataTypeException;
import ca.uhn.hl7v2.model.v251.datatype.*;
import ca.uhn.hl7v2.model.v251.message.EQQ_Q04;

/***
 * Create a EQQ_Q04 HL7 query message send Prescription Drug List object
 * prescription drug list to a patient.
 * @author klanerolle@gmail.com
 *
 */
public class CreateEQQQ04 {
	private EQQ_Q04 qry;
	private PrescriptionDrugs prescriptionDrugs;
	
	/**
	 * Accept a Prescription Drug List object.
	 * @param prescriptionDrugs
	 */	
	public CreateEQQQ04(PrescriptionDrugs prescriptionDrugs){
		this.qry=new EQQ_Q04();
		this.prescriptionDrugs=prescriptionDrugs;
	}
	
	/**
	 * Create the EQQ_Q04 message
	 * @param sendingFacility
	 * @return the EQQ_Q04 Query message
	 * @throws HL7Exception
	 */	
	public String createMessage(String sendingFacility) throws HL7Exception{
		this.addMessageHeader(sendingFacility);
		this.addSearchDetails();
		return qry.getMessage().encode();
	}
	
	/**
	 * Add the MSH segment to the message.
	 * @param sendingFacility
	 * @throws DataTypeException
	 */	
	private void addMessageHeader(String sendingFacility) throws DataTypeException{
		qry.getMSH().getFieldSeparator().setValue("|");
		qry.getMSH().getEncodingCharacters().setValue("^~\\&");
		qry.getMSH().getDateTimeOfMessage().getTime().setValue(Calendar.getInstance().getTime());
		qry.getMSH().getMessageType().getMsg1_MessageCode().setValue("EQQ");
		qry.getMSH().getMessageType().getTriggerEvent().setValue("Q04");
		qry.getMSH().getSendingApplication().getUniversalID().setValue("CSTH");
		qry.getMSH().getVersionID().getVersionID().setValue("2.5.1");
		qry.getMSH().getSendingFacility().getUniversalID().setValue(sendingFacility);
		qry.getMSH().getReceivingApplication().getUniversalID().setValue("PAS");
		qry.getMSH().getReceivingFacility().getUniversalID().setValue(sendingFacility);
	}
	
	/**
	 * Add search details to segments EQL
	 * @throws DataTypeException
	 */
	private void addSearchDetails() throws DataTypeException{		
		qry.getEQL().getEql1_QueryTag().setValue("requested_drugs");
		qry.getEQL().getEql2_QueryResponseFormatCode().setValue("T");
		qry.getEQL().getEql3_EQLQueryName().getCe1_Identifier().setValue("hibernate_qry");
		qry.getEQL().getEql4_EQLQueryStatement().setValue(prescriptionDrugs.getPatientId());		
	}
}
